package com.family.action;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.boot.context.embedded.MultipartConfigFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import com.family.filter.MyFilter;
import javax.servlet.MultipartConfigElement;
import javax.sql.DataSource;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;


@SpringBootApplication
@MapperScan("com.family.inter")
public class Application implements EmbeddedServletContainerCustomizer{

    public static String key="";

    public static String[] args;

    // 创建菜单、菜单项数组、消息类型
    public static PopupMenu popup = new PopupMenu();
    public static MenuItem exitItem = new MenuItem("退出程序");

    // 定义系统托盘、托盘图标变量
    public static SystemTray tray;
    public static TrayIcon trayIcon;


    private static Logger logger = Logger.getLogger(Application.class);

    @Bean
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource dataSource() {
        return new org.apache.tomcat.jdbc.pool.DataSource();
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/com/family/mapper/*.xml"));

        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //// 设置文件大小限制 ,超了，页面会抛出异常信息，这时候就需要进行异常信息的处理了;
        factory.setMaxFileSize("10MB"); //KB,MB
        /// 设置总上传数据总大小
        factory.setMaxRequestSize("1024MB");
        //Sets the directory location where files will be stored.
        //factory.setLocation("路径地址");
        return factory.createMultipartConfig();
    }

    /**
     * 配置过滤器
     * @return
     */
    @Bean
    public FilterRegistrationBean someFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new MyFilter());
        registration.addUrlPatterns("/*");
        registration.addInitParameter("paramName", "paramValue");

        registration.setName("sessionFilter");
        return registration;
    }

    /*端口默认为8080*/
    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        container.setPort(Integer.parseInt(UploadAction.prop.getProperty("port")));
    }


    /**
     * Start
     */
    public static void main(String[] Args) {

        args =Args;

//    	String serial="";
//		/* 获取cpu序列号 */
//		Process process;
//		try {
//			process = Runtime.getRuntime().exec(
//					new String[] { "wmic", "cpu", "get", "ProcessorId" });
//			process.getOutputStream().close();
//			Scanner sc = new Scanner(process.getInputStream());
//			String property = sc.next();
//		    serial = sc.next();
//
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//
//        try {
//
//        	File f = new File("./license.txt");
//        	if(f.exists()==false)
//        	{
//        		 Alert();
//    			 return;
//        	}
//
//			/*读取注册文件*/
//			 FileInputStream in = new FileInputStream(f);
//			 InputStreamReader inReader = new InputStreamReader(in, "UTF-8");
//			 BufferedReader bufReader = new BufferedReader(inReader);
//			 String md5Serial = bufReader.readLine();
//			 String hex = EncrypMD5.eccrypt(serial).toUpperCase();
//
//			 if(hex.equals(md5Serial) == false)
//			 {
//				 Alert();
//				 return;
//			 }
//		} catch (Exception e) {
//			e.printStackTrace();
//			return;
//		}

//    	int flag = DateFormatUtils.DateCompare("20171001");
//    	if(flag>0)
//    	{
//    		 Alert();
//    		 return;
//    	}
//
        SpringApplication.run(Application.class, Application.args);

        /*系统托盘*/
//    	SystemTray();

        //启用cmd运行IE的方式来打开网址。
//		String str = "cmd /c start iexplore -k http://127.0.0.1:"+UploadAction.prop.getProperty("port")+"/";
//		try {
//			Runtime.getRuntime().exec(str);
//		} catch (Exception e1) {
//			e1.printStackTrace();
//		}
//

    }

    //提示用户未注册
    public static void Alert()
    {
        JLabel lbl = new JLabel("软件未注册");


        JFrame frame = new JFrame();

        URL in = Application.class.getClassLoader().getResource("static/img/icon.jpg");
        // 加载图标
        Image image = Toolkit.getDefaultToolkit().createImage(in);

        ImageIcon icon=new ImageIcon(image);
        frame.setIconImage(icon.getImage());


        frame.setTitle("提示");
        lbl.setBounds(60, 20, 100, 20);

        frame.add(lbl);
        //获取屏幕大小
        Dimension screenSize =Toolkit.getDefaultToolkit().getScreenSize();

        frame.setSize(200,100);

        //让窗口居中显示
        frame.setLocation(screenSize.width/2-200/2,screenSize.height/2-100/2);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(null);
        frame.setVisible(true);
    }

    // 构造方法
    public static void SystemTray() {

        /* 点击退出程序退出系统 */
        exitItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        popup.add(exitItem);// 将退出菜单添加到菜单中

        // 判断当前操作系统是否支持系统托盘
        if (SystemTray.isSupported()) {
            // 获取系统托盘
            tray = SystemTray.getSystemTray();

            URL in = Application.class.getClassLoader().getResource("static/img/icon.jpg");

            // 加载图标
            Image image = Toolkit.getDefaultToolkit().createImage(in);
            // 创建托盘图标
            trayIcon = new TrayIcon(image, "系统运行中", popup);
            // 托盘图标自动设置尺寸
            trayIcon.setImageAutoSize(true);
            try {// 添加托盘图标到系统托盘中
                tray.add(trayIcon);
            } catch (AWTException e) {
                e.printStackTrace();
            }
            // 为托盘图标注册监听器
            trayIcon.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {

                    if (e.getSource() == trayIcon) {// 双击托盘图标执行的代码

                        String str = "cmd /c start iexplore -k  http://127.0.0.1:"+UploadAction.prop.getProperty("port")+"/";
                        try {
                            Runtime.getRuntime().exec(str);
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            });
        }
    }

}
